package com.z.security.controller;

import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;

/**
 * @author zhaodf
 */
@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello() {
//        存储登录用户信息。
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        System.out.println("authentication = " + authentication);

        return "hello security";
    }

    @GetMapping("/user")
    public String login(Authentication authentication, Principal principal) {

        System.out.println("authentication = " + authentication);
        System.out.println(" authentication = " + JSONObject.toJSONString(authentication, true));
        System.out.println(" principal = " + JSONObject.toJSONString(principal, true));
        return "user";
    }

    @RequestMapping("/hello2")
    public void hello2(HttpServletRequest request){
        String remoteUser = request.getRemoteUser();
        System.out.println( "remoteUser = " + JSONObject.toJSONString( remoteUser ,true));
        boolean admin = request.isUserInRole("admin");
        System.out.println( "admin = " + JSONObject.toJSONString( admin ,true));
        Principal userPrincipal = request.getUserPrincipal();
        System.out.println( "userPrincipal = " + JSONObject.toJSONString( userPrincipal ,true));
    }
}
